//using System.ComponentModel;
using CodeSmith.Engine;
using System.Data;
using SchemaExplorer;
/*
将表的列名组合成一个串。
kind:1=@shopId int[nvarchar(size)], 
     2:shopId,          
     3: @shopId,  //insert SQL语句  INSERT INTO tableName(col1,col2) values (@col1,@col2)
     4: id_auto=@id_auto, //update语句中用到的 update tableName set col1=@col1,col2=@col2 where pkcol1=@pkcol1 and pkcol2=@pkcol2
     5: @pkcol nvarchar(50),@pkcol2 nvarchar(50)
     6: pkcol1=@pkcol1 and pkcol2=@pkcol2   关键词组合
*/
public class ProcCommonFun : CodeTemplate
{
    public string CombineColumnsStr(SchemaExplorer.TableSchema table,int kind)
    {
        string ret="";
        if(kind==1)
        {
            foreach(ColumnSchema col in table.Columns)
            {
                ret+="@"+col.Name+" "+ColDataType(col.DataType,col.Size)+",\r\n";
            }
        }
        if(kind==2)
        {
            foreach(ColumnSchema col in table.Columns)
            {
                ret+=col.Name+",\r\n";
            }
        }    
        if(kind==3)
        {
            foreach(ColumnSchema col in table.Columns)
            {
                ret+="@"+col.Name+",\r\n";
            }
        }
        if(kind==4)//update
        {
            foreach(ColumnSchema col in table.Columns)
            {
                if(!col.IsPrimaryKeyMember)
                {
                    ret+=col.Name+"=@"+col.Name+",\r\n";
                }
            }
        }
        if(kind==5)
        {
            foreach(MemberColumnSchema pkCol in table.PrimaryKey.MemberColumns)
            {
                ret+="@"+pkCol.Name+" "+ColDataType(pkCol.DataType,pkCol.Size)+",\r\n";
            }
        }
        if(kind==6)
        {
            foreach(MemberColumnSchema pkCol in table.PrimaryKey.MemberColumns)
            {
                ret+=pkCol.Name+"=@"+pkCol.Name+" and ";
            }
        }        
        return ret.Trim(',','\r','\n','a','n','d',' ');
    }

    public string GetTableKeys(SchemaExplorer.TableSchema table)
    {
        return table.PrimaryKey.MemberColumns[0].Name;
    }

    public string ColDataType(System.Data.DbType type,int colSize)
    {
        if(type==DbType.Int32)
        {
            return "int";
        }
        else if(type==DbType.String || type==DbType.AnsiString ||type==DbType.StringFixedLength)
        {
            return "nvarchar("+colSize+")";
        }
        else if(type==DbType.DateTime ||type==DbType.Date)
        {
            return "datetime";
        }
        else
        {
            return type.ToString();
        }
    }
}
